{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "29e5c911-fa2d-4593-8565-3b7bb127b53d",
   "metadata": {},
   "source": [
    "# LangChain 核心模块 Agent - Self ask with search\n",
    "\n",
    "- Google 搜索对接\n",
    "    - 第三方平台：https://serpapi.com\n",
    "    - LangChain API 封装：`SerpAPIWrapper`\n",
    "- LangChain Agent 模块使用\n",
    "    - Agent 类型：`SELF_ASK_WITH_SEARCH`\n",
    "    - Agent 实例化：`initialize_agent` 方法\n",
    " \n",
    "https://python.langchain.com/docs/modules/agents/agent_types/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2866704f-c203-4c97-8221-c2ecadc52b4c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"SERPAPI_API_KEY\"] = \"xxx\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "add0b59e-9e30-41a1-9a4e-bacf8aefb3e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import OpenAI, SerpAPIWrapper\n",
    "from langchain.agents import initialize_agent, AgentType, Tool\n",
    "\n",
    "llm = OpenAI(temperature=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "7047f1b0-a29c-497e-badc-d02fbcbf4082",
   "metadata": {},
   "outputs": [],
   "source": [
    "search = SerpAPIWrapper()\n",
    "tools = [\n",
    "    Tool(\n",
    "        name=\"Intermediate Answer\",\n",
    "        func=search.run,\n",
    "        description=\"useful for when you need to ask with search\",\n",
    "    )\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "08a5daa3-fc7a-4ce9-aa46-ad4a6d31be74",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m Yes.\n",
      "Follow up: 何时举办的成都大运会？\u001b[0m\n",
      "Intermediate answer: \u001b[36;1m\u001b[1;3mFri, Jul 28, 2023, 8:00 AM – Tue, Aug 8, 2023\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mFollow up: 成都大运会是第几届大运会？\u001b[0m\n",
      "Intermediate answer: \u001b[36;1m\u001b[1;3m2021年夏季世界大学生运动会（英语：2021 Summer World University Games）简称为2021年成都大运会或成都大运会，是第31届夏季世界大学生运动会，原定于2021年于中国四川省成都市举行，后因2019冠状病毒病疫情等原因二次延期，最终改至2023年7月28日至8月8日举行。\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mSo the final answer is: 第31届\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'第31届'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "self_ask_with_search = initialize_agent(\n",
    "    tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True\n",
    ")\n",
    "self_ask_with_search.run(\n",
    "    \"成都举办的大运会是第几届大运会？\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "647bdb68-bdb3-4c09-a911-d6a4ef64531b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m Yes.\n",
      "Follow up: 什么是2023年大运会？\u001b[0m\n",
      "Intermediate answer: \u001b[36;1m\u001b[1;3mThe 2023 FISU Summer World University Games, officially known as the 2023 Summer Universiade or the XXXII Summer World University Games, and commonly known as Yekaterinburg 2023 or Ekaterinburg 2023, ...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mwill be the 32nd edition of the Summer Universiade, an international multi-sport event organised for university athletes by the International University Sports Federation (FISU).\n",
      "Follow up: 2023年大运会的举办地在哪里？\u001b[0m\n",
      "Intermediate answer: \u001b[36;1m\u001b[1;3m2023年夏季世界大学生运动会编辑 2023年夏季世界大学生运动会（英语：XXXII 2023 Summer World University Games）简称为叶卡捷琳堡大运会，是第32届夏季世界大学生运动会。 原定于2023年8月8日至19日在俄罗斯叶卡捷琳堡举行。\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mSo the final answer is: Yekaterinburg, Russia\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Yekaterinburg, Russia'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "self_ask_with_search.run(\n",
    "    \"2023年大运会举办地在哪里？\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "ff5ac89a-2eb7-437b-890b-19085dacecc2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m Yes.\n",
      "Follow up: 什么是2023年大运会？\u001b[0m\n",
      "Intermediate answer: \u001b[36;1m\u001b[1;3mThe 2023 FISU Summer World University Games, officially known as the 2023 Summer Universiade or the XXXII Summer World University Games, and commonly known as Yekaterinburg 2023 or Ekaterinburg 2023, ...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mwill be the 32nd edition of the Summer Universiade, an international multi-sport event organised for university athletes by the International University Sports Federation (FISU).\n",
      "Follow up: 2023年大运会的举办地在哪里？\u001b[0m\n",
      "Intermediate answer: \u001b[36;1m\u001b[1;3m2023年夏季世界大学生运动会编辑 2023年夏季世界大学生运动会（英语：XXXII 2023 Summer World University Games）简称为叶卡捷琳堡大运会，是第32届夏季世界大学生运动会。 原定于2023年8月8日至19日在俄罗斯叶卡捷琳堡举行。\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mSo the final answer is: Yekaterinburg, Russia\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Yekaterinburg, Russia'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "self_ask_with_search.run(\n",
    "    \"2023年大运会举办地在哪里？\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "32021fdf-2597-4dde-a425-13650904671f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "2023年大运会将在日本东京举办。\n"
     ]
    }
   ],
   "source": [
    "print(llm(\"2023年大运会举办地在哪里？\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "882a6931-929a-46db-9dae-b16a5c1d195b",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "d98ba940-a6e8-477e-83a9-2e20115ff51d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chat_models import ChatOpenAI\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4\", temperature=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "25978771-8e69-41f2-b9e8-b287d846e1cd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mYes.\n",
      "Follow up: 成都举办的大运会是哪一年的？\u001b[0m\n",
      "Intermediate answer: \u001b[36;1m\u001b[1;3m2021年夏季世界大学生运动会（英语：2021 Summer World University Games）简称为2021年成都大运会或成都大运会，是第31届夏季世界大学生运动会，原定于2021年于中国四川省成都市举行，后因2019冠状病毒病疫情等原因二次延期，最终改至2023年7月28日至8月8日举行。\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mSo the final answer is: 第31届\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'第31届'"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "self_ask_with_search_chat = initialize_agent(\n",
    "    tools, chat_model, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True\n",
    ")\n",
    "self_ask_with_search_chat.run(\n",
    "    \"成都举办的大运会是第几届大运会？\"\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
